package com.youlu.campus.starter.web.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;

/**
 * 枚举序列化器
 */
public class GenericEnumDeserializer extends JsonDeserializer<Enum<?>> implements ContextualDeserializer {
    private Class<? extends Enum> enumClass; // 目标枚举类型

    public GenericEnumDeserializer() {
    }

    public GenericEnumDeserializer(Class<? extends Enum> enumClass) {
        this.enumClass = enumClass;
    }

    @Override
    public Enum<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String value = p.getValueAsString();
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        try {
            // 使用枚举的name()进行转换
            return Enum.valueOf(this.enumClass, value);
        } catch (IllegalArgumentException e) {
            // 处理未知的枚举值，例如返回null或记录日志
            return null;
        }
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        // 获取当前需要反序列化的目标枚举类型
        Class<? extends Enum> targetEnumClass = (Class<? extends Enum>) ctxt.getContextualType().getRawClass();
        return new GenericEnumDeserializer(targetEnumClass);
    }

}